//
//  ICMRepairEventAndPartSearchViewController.m
//  ICrEAM
//
//  Created by FoREVer_SaD on 16/11/2.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMRepairEventAndPartSearchViewController.h"
#import "ICMRepairEventSearchTableViewCell.h"
#import "ICMRepairPartSearchTableViewCell.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMRepairPartsModel.h"

@interface ICMRepairEventAndPartSearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,ICMRepairPartSearchTableViewCellDelegate>

@property (nonatomic, strong) UIView *mainDisplayView;

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) UIButton *selectRepairEventButton;

@property (nonatomic, strong) UIButton *selectRepairPartButton;

@property (nonatomic, strong) UIView *repairEventSelectHeader;

@property (nonatomic, strong) UIView *repairPartSelectHeader;

@property (nonatomic, strong) NSMutableArray *repairEventArray;

@property (nonatomic, strong) NSMutableArray *repairPartArray;

@property (nonatomic, strong) NSMutableArray *selectedEventArray;

@property (nonatomic, strong) NSMutableArray *selectedPartArray;

@property (nonatomic, strong) UITableView *repairSelectionTableView;

@property (nonatomic, assign) BOOL eventHasNext;

@property (nonatomic, assign) BOOL partHasNext;

@property (nonatomic, assign) int eventPageNo;

@property (nonatomic, assign) int partPageNo;

@property (nonatomic, strong) NSString *eventSearchText;

@property (nonatomic, strong) NSString *partSearchText;

@end

@implementation ICMRepairEventAndPartSearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.repairSelectionTableView reloadData];
}

- (NSMutableArray *)repairEventArray{
    if (!_repairEventArray) {
        _repairEventArray = [NSMutableArray array];
    }
    return _repairEventArray;
}

- (NSMutableArray *)repairPartArray{
    if (!_repairPartArray) {
        _repairPartArray = [NSMutableArray array];
    }
    return _repairPartArray;
}

- (NSMutableArray *)selectedEventArray{
    if (!_selectedEventArray) {
        _selectedEventArray = [NSMutableArray array];
    }
    return _selectedEventArray;
}

- (NSMutableArray *)selectedPartArray{
    if (!_selectedPartArray) {
        _selectedPartArray = [NSMutableArray array];
    }
    return _selectedPartArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    
//    self.repairEventArray = [NSMutableArray arrayWithArray:@[@(1), @(2), @(3)]];
//    self.repairPartArray = [NSMutableArray arrayWithArray:@[@(1), @(2), @(3)]];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didchange:) name:UITextFieldTextDidChangeNotification object:self];
    
    UIButton *blankView = [UIButton buttonWithType:UIButtonTypeCustom];
    blankView.frame = self.view.bounds;
    blankView.backgroundColor = BackgroundColor_Tanslucent_black;
    [blankView addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:blankView];
    
    UIView *mainDisplayView = [[UIView alloc] initWithFrame:CGRectMake(ActualWidth(50), ActualHeight(110), ActualWidth(924), ActualHeight(565))];
    mainDisplayView.backgroundColor = BackgroundColor_White;
    BorderColor(mainDisplayView, BorderColor_Gray_Hex);
    BorderWidth(mainDisplayView, 1.0);
    CornerRadius(mainDisplayView, 4.0);
    [self.view addSubview:mainDisplayView];
    self.mainDisplayView = mainDisplayView;
    
    UITapGestureRecognizer *backgroundGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCancelButton)];
    [blankView addGestureRecognizer:backgroundGesture];
    
    
//    UITapGestureRecognizer *mainDisplayGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doNothing)];
//    [mainDisplayView addGestureRecognizer:mainDisplayGesture];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(ActualWidth(140), ActualHeight(64), ActualWidth(585), ActualHeight(30))];
    searchView.backgroundColor = [UIColor clearColor];
    CornerRadius(searchView, ActualHeight(30)/2);
    BorderColor(searchView, BorderColor_Gray_Hex);
    BorderWidth(searchView, 1.0);
    [mainDisplayView addSubview:searchView];
    
    
    UIImageView *searchImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:GetCar_SearchIcon]];
    searchImageView.frame = CGRectMake(ActualWidth(10), ActualHeight(5), ActualHeight(20), ActualHeight(20));
    searchImageView.contentMode = UIViewContentModeScaleAspectFit;
    [searchView addSubview:searchImageView];
    
    UITextField *searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(searchImageView.rightEdge, 0, ActualWidth(530), searchView.height)];
    searchTextField.placeholder = @"项目名称、项目代码";
    searchTextField.font = ContentFont;
    [searchView addSubview:searchTextField];
    searchTextField.returnKeyType = UIReturnKeySearch;
    searchTextField.keyboardType = UIReturnKeySearch;
    searchTextField.delegate = self;
    self.searchTextField = searchTextField;
    
    UIImageView *deleteImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sc"]];
    deleteImageView.frame = CGRectMake(ActualWidth(550), ActualHeight(5), ActualHeight(20), ActualHeight(20));
    deleteImageView.contentMode = UIViewContentModeScaleAspectFit;
    [searchView addSubview:deleteImageView];
    
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteButton.frame = CGRectMake(ActualWidth(550), 0, ActualWidth(35), ActualHeight(30));
    [deleteButton addTarget:self action:@selector(deleteSearchContentText) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:deleteButton];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(searchView.rightEdge+ActualWidth(10), searchView.centerY-8, 50, 16);
    [cancelButton addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTitleColor:TitleColor_Dark forState:UIControlStateNormal];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = ContentFont;
    [mainDisplayView addSubview:cancelButton];
    
    UIButton *selectRepairEventButton = [UIButton buttonWithType:UIButtonTypeCustom];
    selectRepairEventButton.frame = CGRectMake(ActualWidth(307), searchView.bottomEdge+ActualHeight(20), ActualWidth(130), ActualWidth(30));
    [selectRepairEventButton setUpButtonWithNormolTitle:@"选择维修项目" selectedTitle:@"选择维修项目" normolTitleSize:ActualWidth(18) selectedTitleSize:ActualWidth(18) normolTitleColor:ContentTextColor_Gray selectedTitleColor:TitleColor_Dark normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(clickSelectButton:) target:self];
    selectRepairEventButton.selected = YES;
    self.selectIndex = 0;
    self.selectRepairEventButton = selectRepairEventButton;
    [self.mainDisplayView addSubview:selectRepairEventButton];
    
    UIView *selectBtnSep = [[UIView alloc] initWithFrame:CGRectMake(selectRepairEventButton.rightEdge+ActualWidth(25), selectRepairEventButton.y, 1.0, selectRepairEventButton.height)];
    selectBtnSep.backgroundColor = SepColor_gray;
    [self.mainDisplayView addSubview:selectBtnSep];
    
    UIButton *selectRepairPartButton = [UIButton buttonWithType:UIButtonTypeCustom];
    selectRepairPartButton.frame = CGRectMake(selectRepairEventButton.rightEdge+ActualWidth(50), selectRepairEventButton.y, ActualWidth(130), ActualHeight(30));
    [selectRepairPartButton setUpButtonWithNormolTitle:@"选择维修零件" selectedTitle:@"选择维修零件" normolTitleSize:ActualWidth(18) selectedTitleSize:ActualWidth(18) normolTitleColor:ContentTextColor_Gray selectedTitleColor:TitleColor_Dark normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(clickSelectButton:) target:self];
    self.selectRepairPartButton = selectRepairPartButton;
    [self.mainDisplayView addSubview:selectRepairPartButton];
    
    [self setupSelectHeaderView];
    
    UITableView *repairSelectionTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.repairEventSelectHeader.bottomEdge, mainDisplayView.width, ActualHeight(264)) style:UITableViewStylePlain];
    repairSelectionTableView.delegate = self;
    repairSelectionTableView.dataSource = self;
    repairSelectionTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    repairSelectionTableView.backgroundColor = [UIColor clearColor];
    [repairSelectionTableView registerClass:[ICMRepairEventSearchTableViewCell class] forCellReuseIdentifier:@"ICMRepairEventSearchTableViewCell"];
    [repairSelectionTableView registerClass:[ICMRepairPartSearchTableViewCell class] forCellReuseIdentifier:@"ICMRepairPartSearchTableViewCell"];
    repairSelectionTableView.tableFooterView = [[UIView alloc] init];
    [self.mainDisplayView addSubview:repairSelectionTableView];
    self.repairSelectionTableView = repairSelectionTableView;
    [repairSelectionTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(mainDisplayView.mas_left);
        make.right.equalTo(mainDisplayView.mas_right);
        make.bottom.equalTo(mainDisplayView.mas_bottom);
        make.top.equalTo(self.repairEventSelectHeader.mas_bottom);
    }];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.searchTextField];
    self.partHasNext = YES;
    self.eventHasNext = YES;
}

- (void)setupSelectHeaderView{
    
    UIView *repairEventSelectHeader = [[UIView alloc] initWithFrame:CGRectMake(0, self.selectRepairEventButton.bottomEdge+ActualHeight(35), self.mainDisplayView.width, ActualHeight(44))];
    repairEventSelectHeader.backgroundColor = [UIColor clearColor];
    [self.mainDisplayView addSubview:repairEventSelectHeader];
    self.repairEventSelectHeader = repairEventSelectHeader;
    
    UILabel *eventOperateLabel = [self createLabelWithText:@"操作" frame:CGRectMake(0, ActualHeight(14), ActualWidth(96), ActualHeight(16))];
    [repairEventSelectHeader addSubview:eventOperateLabel];
    
    UIView *firstEventSep = [[UIView alloc] initWithFrame:CGRectMake(eventOperateLabel.rightEdge, 0, 1, repairEventSelectHeader.height)];
    firstEventSep.backgroundColor = SepColor_gray;
    [repairEventSelectHeader addSubview:firstEventSep];
    
    UILabel *eventNameLabel = [self createLabelWithText:@"项目名称" frame:CGRectMake(firstEventSep.rightEdge, eventOperateLabel.y, ActualWidth(420), ActualHeight(16))];
    [repairEventSelectHeader addSubview:eventNameLabel];
    
    UIView *secondEventSep = [[UIView alloc] initWithFrame:CGRectMake(eventNameLabel.rightEdge, 0, 1, repairEventSelectHeader.height)];
    secondEventSep.backgroundColor = SepColor_gray;
    [repairEventSelectHeader addSubview:secondEventSep];
    
    UILabel *workingTimeLabel = [self createLabelWithText:@"执行工时" frame:CGRectMake(secondEventSep.rightEdge, eventNameLabel.y, ActualWidth(155), ActualHeight(16))];
    [repairEventSelectHeader addSubview:workingTimeLabel];
    
    UIView *thirdEventSep = [[UIView alloc] initWithFrame:CGRectMake(workingTimeLabel.rightEdge, 0, 1, repairEventSelectHeader.height)];
    thirdEventSep.backgroundColor = SepColor_gray;
    [repairEventSelectHeader addSubview:thirdEventSep];
    
    UILabel *deviationLabel = [self createLabelWithText:@"偏差" frame:CGRectMake(thirdEventSep.rightEdge, workingTimeLabel.y, self.mainDisplayView.width-thirdEventSep.rightEdge, ActualHeight(16))];
    [repairEventSelectHeader addSubview:deviationLabel];
    
    UIView *repairPartSelectHeader = [[UIView alloc] initWithFrame:CGRectMake(0, self.selectRepairEventButton.bottomEdge+ActualHeight(35), self.mainDisplayView.width, ActualHeight(44))];
    repairPartSelectHeader.backgroundColor = [UIColor clearColor];
    [self.mainDisplayView addSubview:repairPartSelectHeader];
    repairPartSelectHeader.hidden = YES;
    self.repairPartSelectHeader = repairPartSelectHeader;
    
    UILabel *partOperateLabel = [self createLabelWithText:@"操作" frame:CGRectMake(0, ActualHeight(14), ActualWidth(96), ActualHeight(16))];
    [repairPartSelectHeader addSubview:partOperateLabel];
    
    UIView *firstPartSep = [[UIView alloc] initWithFrame:CGRectMake(partOperateLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    firstPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:firstPartSep];
    
    UILabel *partNameLabel = [self createLabelWithText:@"零件名称" frame:CGRectMake(firstPartSep.rightEdge, partOperateLabel.y, ActualWidth(150), ActualHeight(16))];
    [repairPartSelectHeader addSubview:partNameLabel];
    
    UIView *secondPartSep = [[UIView alloc] initWithFrame:CGRectMake(partNameLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    secondPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:secondPartSep];
    
    UILabel *partPropertyLabel = [self createLabelWithText:@"零件属性" frame:CGRectMake(secondPartSep.rightEdge, partNameLabel.y, ActualWidth(105), ActualHeight(16))];
    [repairPartSelectHeader addSubview:partPropertyLabel];
    
    UIView *thirdPartSep = [[UIView alloc] initWithFrame:CGRectMake(partPropertyLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    thirdPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:thirdPartSep];
    
    UILabel *stockPlaceLabel = [self createLabelWithText:@"库位" frame:CGRectMake(thirdPartSep.rightEdge, partPropertyLabel.y, ActualWidth(150), ActualHeight(16))];
    [repairPartSelectHeader addSubview:stockPlaceLabel];
    
    UIView *fourthPartSep = [[UIView alloc] initWithFrame:CGRectMake(stockPlaceLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    fourthPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:fourthPartSep];
    
    UILabel *stockNumberLabel = [self createLabelWithText:@"可用库存" frame:CGRectMake(fourthPartSep.rightEdge, partNameLabel.y, ActualWidth(90), ActualHeight(16))];
    [repairPartSelectHeader addSubview:stockNumberLabel];
    
    UIView *fifthPartSep = [[UIView alloc] initWithFrame:CGRectMake(stockNumberLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    fifthPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:fifthPartSep];
    
    UILabel *priceLabel = [self createLabelWithText:@"价格" frame:CGRectMake(fifthPartSep.rightEdge, partNameLabel.y, ActualWidth(96), ActualHeight(16))];
    [repairPartSelectHeader addSubview:priceLabel];
    
    UIView *sixthPartSep = [[UIView alloc] initWithFrame:CGRectMake(priceLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
    sixthPartSep.backgroundColor = SepColor_gray;
    [repairPartSelectHeader addSubview:sixthPartSep];
    
    UILabel *quantityLabel = [self createLabelWithText:@"数量" frame:CGRectMake(sixthPartSep.rightEdge, priceLabel.y, self.hasPartLeft?ActualWidth(110):self.mainDisplayView.width-sixthPartSep.rightEdge, ActualHeight(16))];
    [repairPartSelectHeader addSubview:quantityLabel];
    
    if (self.hasPartLeft) {
        UIView *seventhPartSep = [[UIView alloc] initWithFrame:CGRectMake(quantityLabel.rightEdge, 0, 1, repairPartSelectHeader.height)];
        seventhPartSep.backgroundColor = SepColor_gray;
        [repairPartSelectHeader addSubview:seventhPartSep];
        
        UILabel *leftLabel = [self createLabelWithText:@"留存" frame:CGRectMake(seventhPartSep.rightEdge, quantityLabel.y, self.mainDisplayView.width-seventhPartSep.rightEdge, ActualHeight(16))];
        [repairPartSelectHeader addSubview:leftLabel];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selectIndex == 0) {
        return self.repairEventArray.count;
    } else if (self.selectIndex == 1) {
        return self.repairPartArray.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ActualHeight(95);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectIndex == 0) {
        ICMRepairEventSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMRepairEventSearchTableViewCell"];
        if (!cell) {
            cell = [[ICMRepairEventSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMRepairEventSearchTableViewCell"];
        }
        ICMRepairMaintenanceModel *model = self.repairEventArray[indexPath.row];
        [cell setupLabelsWithModel:model];
        if ([self.selectedEventArray containsObject:model]) {
            cell.eventOperateButton.selected = YES;
        } else {
           cell.eventOperateButton.selected = NO;
        }
        
        return cell;
        
    } else if (self.selectIndex == 1) {
        ICMRepairPartSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMRepairPartSearchTableViewCell"];
        if (!cell) {
            cell = [[ICMRepairPartSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ICMRepairPartSearchTableViewCell"];
        }
        cell.delegate = self;
        ICMRepairPartsModel *model = self.repairPartArray[indexPath.row];
        cell.hasPartLeft = self.hasPartLeft;
        [cell setupLabelsWithModel:model];
        if ([self.selectedPartArray containsObject:cell.model]) {
            cell.eventOperateButton.selected = YES;
        } else {
            cell.eventOperateButton.selected = NO;
        }
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectIndex == 0) {
        ICMRepairEventSearchTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        BOOL isExist = NO;
//        for (ICMRepairMaintenanceModel *model in self.existRepairEventArray) {
//            if ([model.LABOUR_CODE isEqualToString:cell.model.LABOUR_CODE]) {
//                isExist = YES;
//                break;
//            }
//        }
        if (isExist) {
            [self.view showString:@"不能添加相同的项目" forSeconds:1.5];
        } else {
            if ([self.selectedEventArray containsObject:cell.model]) {
                cell.model.UPDATE_STATUS = @"";
                [self.selectedEventArray removeObject:cell.model];
            } else {
                cell.model.UPDATE_STATUS = @"A";
                [self.selectedEventArray addObject:cell.model];
            }
            cell.eventOperateButton.selected = !cell.eventOperateButton.selected;
            NSString *showString = cell.eventOperateButton.selected?@"添加成功！":@"取消添加成功！";
            [self.view showString:showString forSeconds:1.5];
        }
    } /*else if (self.selectIndex == 1) {
        ICMRepairPartSearchTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        BOOL isExit = NO;
        for (ICMRepairPartsModel *model in self.existRepairPartsArray) {
            if ([model.PART_NO isEqualToString:cell.model.PART_NO]&&[model.STORAGE_POSITION_CODE isEqualToString:cell.model.STORAGE_POSITION_CODE]) {
                isExit = YES;
            }
        }
        if (isExit) {
            [self.view showString:@"不能添加相同的零件" forSeconds:1.5];
            return;
        }
        
        if (cell.quantity>0) {
            if ([self.selectedPartArray containsObject:cell.model]) {
                cell.model.UPDATE_STATUS = @"";
                [self.selectedPartArray removeObject:cell.model];
            } else {
                cell.model.UPDATE_STATUS = @"A";
                [self.selectedPartArray addObject:cell.model];
            }
            cell.eventOperateButton.selected = !cell.eventOperateButton.selected;
            NSString *showString = cell.eventOperateButton.selected?@"添加成功！":@"取消添加成功！";
            [self.view showString:showString forSeconds:1.5];
        }
    }*/
}

#pragma mark -- /*ICMRepairPartSearchTableViewCellDelegate*/
//选择零件
- (void)selectPartWithCell:(ICMRepairPartSearchTableViewCell *)cell {
    BOOL isExit = NO;
    for (ICMRepairPartsModel *model in self.existRepairPartsArray) {
        if ([model.PART_NO isEqualToString:cell.model.PART_NO]&&[model.STORAGE_POSITION_CODE isEqualToString:cell.model.STORAGE_POSITION_CODE]) {
            isExit = YES;
        }
    }
    if (isExit) {
        [self.view showString:@"不能添加相同的零件" forSeconds:1.5];
        return;
    }
    
    if (cell.quantity>0) {
        if ([self.selectedPartArray containsObject:cell.model]) {
            cell.model.UPDATE_STATUS = @"";
            [self.selectedPartArray removeObject:cell.model];
        } else {
            cell.model.UPDATE_STATUS = @"A";
            [self.selectedPartArray addObject:cell.model];
        }
        cell.eventOperateButton.selected = !cell.eventOperateButton.selected;
        NSString *message = @"添加成功！";
        if([cell.model.REAL_QUANTITY floatValue]<[cell.model.OBLIGATED_QUANTITY floatValue]){
            message = [NSString stringWithFormat:@"%@添加的配件数量大于可用库存，将引起负库存。",message];
        }
        
        NSString *showString = cell.eventOperateButton.selected?message:@"取消添加成功！";
        [self.view showString:showString forSeconds:1.5];
    }
}

- (void)repairPartSearchTableViewCell:(ICMRepairPartSearchTableViewCell *)cell andQuantity:(NSInteger)quantity{
    if (quantity == 0) {
        cell.eventOperateButton.selected = NO;
        if ([self.selectedPartArray containsObject:cell.model]) {
            [self.selectedPartArray removeObject:cell.model];
        }
        return;
    }
    if (cell.eventOperateButton.selected) {
        cell.model.OBLIGATED_QUANTITY = [@(quantity) stringValue];
        cell.model.UPDATE_STATUS = @"U";
    }
}

- (void)quantityNotEnough:(NSString *)message{
    [self.view showString:message forSeconds:1.5];
}

- (void)deleteSearchContentText{
    self.searchTextField.text = @"";
}

- (void)clickCancelButton{
    if ([self.delegate respondsToSelector:@selector(getSelectedRepairEvents:repairParts:)]) {
        [self.delegate getSelectedRepairEvents:self.selectedEventArray repairParts:self.selectedPartArray];
    }
    [self.view removeFromSuperview];
    [self.repairSelectionTableView reloadData];
    [self.selectedEventArray removeAllObjects];
    [self.selectedPartArray removeAllObjects];
}

- (void)doNothing{
}

- (void)clickSelectButton:(UIButton *)sender{
    if (sender.selected) {
        return;
    }
    
    if (sender == self.selectRepairEventButton) {
        self.selectRepairEventButton.selected = YES;
        self.repairEventSelectHeader.hidden = NO;
        self.selectRepairPartButton.selected = NO;
        self.repairPartSelectHeader.hidden = YES;
        self.selectIndex = 0;
        self.searchTextField.placeholder = @"项目名称、项目代码";
    } else if (sender == self.selectRepairPartButton) {
        self.selectRepairPartButton.selected = YES;
        self.repairPartSelectHeader.hidden = NO;
        self.selectRepairEventButton.selected = NO;
        self.repairEventSelectHeader.hidden = YES;
        self.selectIndex = 1;
        self.searchTextField.placeholder = @"零件名称、零件代码";
    }
    [self setRefreshAgain];
    [self.repairSelectionTableView reloadData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self setRefresh];
    if (self.selectIndex == 0) {
        self.eventSearchText = self.searchTextField.text;
        [self getRepairEventData];
    } else if (self.selectIndex == 1) {
        self.partSearchText = self.searchTextField.text;
        [self getRepairPartsData];
    }
    return YES;
}

//重新设置上拉加载
- (void)setRefreshAgain {
    //因为用的是同一个tableview，所以当一方没有值，就要重新设置刷新的footer
    if (self.selectIndex == 0 && !self.partHasNext) {
        __weak ICMRepairEventAndPartSearchViewController *my = self;
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.selectIndex == 0) {
                self.eventPageNo++;
                [my getRepairEventData];
            } else {
                self.partPageNo++;
                [my getRepairPartsData];
            }
        }];
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
        [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
        self.self.repairSelectionTableView.mj_footer = footer;
    }

    if (self.selectIndex == 1 && !self.eventHasNext) {
        __weak ICMRepairEventAndPartSearchViewController *my = self;
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.selectIndex == 0) {
                self.eventPageNo++;
                [my getRepairEventData];
            } else {
                self.partPageNo++;
                [my getRepairPartsData];
            }
        }];
        
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
        [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
        self.self.repairSelectionTableView.mj_footer = footer;
    }
}

//上拉加载
- (void)setRefresh {
    if (self.selectIndex == 0) {
        self.eventHasNext = YES;
        self.eventPageNo = 1;
        [self.repairEventArray removeAllObjects];
    } else {
        self.partHasNext = YES;
        self.partPageNo = 1;
        [self.repairPartArray removeAllObjects];
    }
    
    __weak ICMRepairEventAndPartSearchViewController *my = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        if (self.hasNext) {
            if (self.selectIndex == 0) {
                self.eventPageNo++;
                [my getRepairEventData];
            } else {
                self.partPageNo++;
                [my getRepairPartsData];
            }
//        } else {
//            [self.repairSelectionTableView.mj_footer endRefreshingWithNoMoreData];
//        }
    }];
    
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据了" forState:MJRefreshStateNoMoreData];
    self.self.repairSelectionTableView.mj_footer = footer;
}

- (void)getRepairEventData{
    ICMRequestManager *manager = [[ICMRequestManager alloc] init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.eventSearchText forKey:@"KEY_WORD"];
    [parameters setObject:self.modelCode?:@"" forKey:@"MODEL_CODE"];
    [parameters setObject:@(self.eventPageNo) forKey:@"CURRENT_PAGE"];
    if ([self.modelCode isEqualToString:@""]) {
        [self.view showString:@"车型没有填写!" forSeconds:1.5];
    }
    [manager startGetRequestWithURL:RepairEventSearchUrl parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
//            [self.repairEventArray removeAllObjects];
            if (data[@"TM_REPAIR_ITEM_EX"]
                &&
                [data[@"TM_REPAIR_ITEM_EX"] isKindOfClass:[NSArray class]]) {
                if (((NSArray *)data[@"TM_REPAIR_ITEM_EX"]).count > 0) {
                    self.eventHasNext = YES;
                    [self.repairSelectionTableView.mj_footer endRefreshing];
                    for (NSDictionary *dic in data[@"TM_REPAIR_ITEM_EX"]) {
                        ICMRepairMaintenanceModel *model = [ICMRepairMaintenanceModel yy_modelWithDictionary:dic];
                        if(!model.LABOUR_AMOUNT || [model.LABOUR_AMOUNT isEqualToString:@""])
                        {
                            model.LABOUR_AMOUNT = @"0";
                        }
                        model.STD_LABOUR_HOUR = [NSString stringWithFormat:@"%.2f", [model.STD_LABOUR_HOUR floatValue]];
                        if(!model.LABOUR_PRICE || [model.LABOUR_PRICE isEqualToString:@""] || [model.LABOUR_PRICE isKindOfClass:[NSArray class]])
                        {
                            model.LABOUR_PRICE = @"0";
                        }
                        model.LABOUR_PRICE = [NSString stringWithFormat:@"%.2f", [model.LABOUR_PRICE floatValue]];
                        model.TROUBLE_DESC = @"";
                        model.DISCOUNT = 1.0;
                        model.editType = RepairMaintenanceEditTypeAdd;
                        
                        //LABOUR_ID -> REPAIR_ITEM_ID
                        model.LABOUR_ID = model.REPAIR_ITEM_ID;
                        
                        [self.repairEventArray addObject:model];
                    }
                } else {
                    self.eventHasNext = NO;
                    if (self.repairEventArray.count == 0) {
                        self.repairSelectionTableView.mj_footer.hidden = YES;
                        [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                    } else {
//                        self.eventHasNext = NO;
                        [self.repairSelectionTableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
            } else {
                self.eventHasNext = NO;
                if (self.repairEventArray.count == 0) {
                    self.repairSelectionTableView.mj_footer.hidden = YES;
                    [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                } else {
//                    self.eventHasNext = NO;
                    [self.repairSelectionTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            [self.repairSelectionTableView reloadData];
        } else {
            [self.repairSelectionTableView.mj_footer endRefreshing];
        }
    }];
}

- (void)getRepairPartsData{
    ICMRequestManager *manager = [[ICMRequestManager alloc] init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.partSearchText forKey:@"KEY_WORD"];
    [parameters setObject:@(self.partPageNo) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:RepairPartsSearchUrl parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
//            [self.repairPartArray removeAllObjects];
            if (data[@"TM_PART_STOCK"]
                &&
                [data[@"TM_PART_STOCK"] isKindOfClass:[NSArray class]]) {
                if (((NSArray *)data[@"TM_PART_STOCK"]).count > 0) {
                    self.partHasNext = YES;
                    [self.repairSelectionTableView.mj_footer endRefreshing];
                    for (NSDictionary *dic in data[@"TM_PART_STOCK"]) {
                        ICMRepairPartsModel *model = [ICMRepairPartsModel yy_modelWithDictionary:dic];

                        model.OBLIGATED_QUANTITY = @"1.00";
                        model.SALES_PRICE = [NSString stringWithFormat:@"%.2f", [model.SALES_PRICE floatValue]];
                        model.PART_SALES_AMOUNT = [NSString stringWithFormat:@"%.2f", [model.PART_SALES_AMOUNT floatValue]];
                        ParameterModel *temp = [ICrEAMTool getParameterWithCode:model.PART_SORT];
                        model.PART_SORT = [ICrEAMTool getDeatilCodeWithParameterDesc:temp.desc withCode:@"2302"];
                        model.DISCOUNT = 1.0;
                        model.editType = RepairPartEditTypeAdd;
                        model.IS_OBLIGATED = nil;
                        
                        [self.repairPartArray addObject:model];
                    }
                } else {
                    self.partHasNext = NO;
                    if (self.repairPartArray.count == 0) {
                        self.repairSelectionTableView.mj_footer.hidden = YES;
                        [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                    } else {
//                        self.partHasNext = NO;
                        [self.repairSelectionTableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    
                }
            } else {
                self.partHasNext = NO;
                if (self.repairPartArray.count == 0) {
                    self.repairSelectionTableView.mj_footer.hidden = YES;
                    [self.view showString:@"暂无相关搜索结果！" forSeconds:1.5];
                } else {
//                    self.partHasNext = NO;
                    [self.repairSelectionTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            [self.repairSelectionTableView reloadData];
        } else {
            [self.repairSelectionTableView.mj_footer endRefreshing];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UILabel *)createLabelWithText:(NSString *)text frame:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = TitleFont;
    label.textColor = TitleColor_Dark;
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

//默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}


@end
